import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api', // 后端API基础路径
  timeout: 10000,
  withCredentials: true // 支持session
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    // 如果后端返回了错误响应，提取错误信息
    if (error.response && error.response.data) {
      return Promise.reject(error.response.data)
    }
    return Promise.reject(error)
  }
)

// 邮件设置接口
export interface EmailSettings {
  id?: number
  smtpServer: string
  smtpPort: number
  senderEmail: string
  emailPassword: string
  useSsl: boolean
  createdAt?: string
  updatedAt?: string
}

// 通知设置接口
export interface NotificationSettings {
  id?: number
  notifyOnCreate: boolean
  notifyOnStatusChange: boolean
  notifyOnDelivered: boolean
  createTemplate: string
  statusChangeTemplate: string
  deliveredTemplate: string
  createdAt?: string
  updatedAt?: string
}

// API响应格式
export interface ApiResponse<T> {
  code: number
  message: string
  data: T
}

// 管理员订单API响应接口
export interface AdminOrderListResponse {
  list: any[]
  total: number
  pageNum: number
  pageSize: number
  totalPages: number
}

export interface OrderStatistics {
  totalOrders: number
  waitingPickup: number
  waitingShipment: number
  inTransit: number
  waitingDelivery: number
  completed: number
  todayOrders: number
  monthOrders: number
}

/**
 * 获取邮件设置
 */
export function getEmailSettings(): Promise<ApiResponse<EmailSettings>> {
  return api({
    url: '/admin/email-settings',
    method: 'get'
  })
}

/**
 * 更新邮件设置
 */
export function updateEmailSettings(data: Partial<EmailSettings>): Promise<ApiResponse<any>> {
  return api({
    url: '/admin/email-settings',
    method: 'put',
    data
  })
}

/**
 * 获取通知设置
 */
export function getNotificationSettings(): Promise<ApiResponse<NotificationSettings>> {
  return api({
    url: '/admin/notification-settings',
    method: 'get'
  })
}

/**
 * 更新通知设置
 */
export function updateNotificationSettings(data: Partial<NotificationSettings>): Promise<ApiResponse<any>> {
  return api({
    url: '/admin/notification-settings',
    method: 'put',
    data
  })
}

/**
 * 测试邮件连接
 */
export function testEmailConnection(data: EmailSettings): Promise<ApiResponse<any>> {
  return api({
    url: '/admin/email-settings/test',
    method: 'post',
    data
  })
}

// 管理员订单管理接口
export const adminApi = {
  // 获取所有订单信息
  getAllOrders: (params: {
    pageNum?: number
    pageSize?: number
    orderStatus?: number
    keyword?: string
    startDate?: string
    endDate?: string
  } = {}): Promise<ApiResponse<AdminOrderListResponse>> => {
    const queryParams = new URLSearchParams()
    
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined && value !== null && value !== '') {
        queryParams.append(key, value.toString())
      }
    })
    
    const queryString = queryParams.toString()
    const url = `/admin/orders${queryString ? `?${queryString}` : ''}`
    
    console.log('管理员获取订单列表:', url)
    return api.get(url)
  },

  // 获取订单详情
  getOrderDetail: (orderId: number): Promise<ApiResponse<any>> => {
    console.log('管理员获取订单详情:', orderId)
    return api.get(`/admin/orders/${orderId}`)
  },

  // 更新订单状态
  updateOrderStatus: (orderId: number, orderStatus: number, remark?: string): Promise<ApiResponse<any>> => {
    const formData = new FormData()
    formData.append('orderStatus', orderStatus.toString())
    if (remark) {
      formData.append('remark', remark)
    }
    
    console.log('管理员更新订单状态:', { orderId, orderStatus, remark })
    return api.put(`/admin/orders/${orderId}/status`, formData)
  },

  // 获取订单统计信息
  getOrderStatistics: (): Promise<ApiResponse<OrderStatistics>> => {
    console.log('管理员获取订单统计')
    return api.get('/admin/orders/statistics')
  },

  // 删除订单
  deleteOrder: (orderId: number): Promise<ApiResponse<any>> => {
    console.log('管理员删除订单:', orderId)
    return api.delete(`/admin/orders/${orderId}`)
  }
}

// 管理员仪表盘相关接口
export interface DashboardData {
  totalOrders: {
    count: number
    growth: number
    isUp: boolean
  }
  inTransitOrders: {
    count: number
    growth: number
    isUp: boolean
  }
  todayDelivered: {
    count: number
    growth: number
    isUp: boolean
  }
  todayRevenue: {
    amount: number
    growth: number
    isUp: boolean
  }
  todayNewOrders: number
  systemStatus: string
}

export interface DashboardOrderStats {
  waitingPickup: number
  waitingShipment: number
  inTransit: number
  waitingDelivery: number
  completed: number
  todayOrders: number
  weekOrders: number
  monthOrders: number
}

export interface RevenueStats {
  todayRevenue: number
  weekRevenue: number
  monthRevenue: number
  totalRevenue: number
  todayGrowth: number
  weekGrowth: number
  monthGrowth: number
}

// 仪表盘API
export const dashboardApi = {
  // 获取仪表盘完整数据
  getDashboardData: (): Promise<ApiResponse<DashboardData>> => {
    console.log('获取仪表盘数据')
    return api.get('/admin/dashboard')
  },

  // 获取今日新订单数
  getTodayOrders: (): Promise<ApiResponse<{ count: number; message: string }>> => {
    console.log('获取今日新订单数')
    return api.get('/admin/dashboard/today-orders')
  },

  // 获取订单统计概览
  getOrderStats: (): Promise<ApiResponse<DashboardOrderStats>> => {
    console.log('获取订单统计概览')
    return api.get('/admin/dashboard/order-stats')
  },

  // 获取收入统计
  getRevenueStats: (): Promise<ApiResponse<RevenueStats>> => {
    console.log('获取收入统计')
    return api.get('/admin/dashboard/revenue-stats')
  }
}

/**
 * 设置API统一导出对象
 */
export const settingsApi = {
  // 邮件设置
  getEmailSettings,
  updateEmailSettings,
  testEmailConnection,
  
  // 通知设置
  getNotificationSettings,
  updateNotificationSettings
} 